package com.xhtt.modules.cfg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhtt.common.exception.RRException;
import com.xhtt.common.utils.CopyUtils;
import com.xhtt.common.utils.PageUtils;
import com.xhtt.common.utils.Query;
import com.xhtt.modules.cfg.dao.CfgPotInfoMapper;
import com.xhtt.modules.cfg.entity.*;
import com.xhtt.modules.cfg.model.RelateObj;
import com.xhtt.modules.cfg.schedule.PotLog;
import com.xhtt.modules.cfg.service.CfgPotInfoService;
import com.xhtt.modules.cfg.service.CfgPotLogService;
import com.xhtt.modules.cfg.service.CfgPotProductService;
import com.xhtt.modules.cfg.service.CfgPotRelateService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 罐库 服务实现类
 * </p>
 *
 * @author feipc
 * @since 2019-02-21
 */
@Service
public class CfgPotInfoServiceImpl extends ServiceImpl<CfgPotInfoMapper, CfgPotInfo> implements CfgPotInfoService {
    @Autowired
    private CfgPotRelateService potRelateService;
    @Autowired
    private CfgPotProductService cfgPotProductService;
    @Autowired
    private CfgPotLogService potLogService;
    @Resource
    private ThreadPoolTaskExecutor taskExecutor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<CfgPotInfo> page = new Query<CfgPotInfo>(params).getPage();
        List<CfgPotInfo> list = baseMapper.queryPage(page, params);
        //连接点
//        for (CfgPotInfo potInfo : list) {
//            List<CfgPotRelate> potRelates = potRelateService.list(new LambdaQueryWrapper<CfgPotRelate>().eq(CfgPotRelate::getPotId, potInfo.getId()));
//            List<CfgPotRelate> guan = potRelates.stream().filter(cfgPotRelate -> cfgPotRelate.getType().intValue() == 1).collect(Collectors.toList());//罐
//            List<CfgPotRelate> yingguan = potRelates.stream().filter(cfgPotRelate -> cfgPotRelate.getType().intValue() == 2).collect(Collectors.toList());//硬管
//            List<CfgPotRelate> beng = potRelates.stream().filter(cfgPotRelate -> cfgPotRelate.getType().intValue() == 3).collect(Collectors.toList());//泵
//            List<CfgPotRelate> matou = potRelates.stream().filter(cfgPotRelate -> cfgPotRelate.getType().intValue() == 4).collect(Collectors.toList());//码
//            potInfo.setRelateObject("待完善连接点 todo");
//        }

        page.setRecords(list);
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void addPot(CfgPotInfo cfgPotInfo) {
        String numberNo = cfgPotInfo.getNumberNo();
        int count = this.count(new LambdaQueryWrapper<CfgPotInfo>().eq(CfgPotInfo::getNumberNo, numberNo).ne(CfgPotInfo::getStatus, -1));
        if (count > 0) {
            throw new RRException("编号已存在");
        }
        cfgPotInfo.setStatus(1);
        this.save(cfgPotInfo);
        CfgPotProduct potProduct = cfgPotInfo.getPotProduct();
        if (null != potProduct) {
            potProduct.setPotId(cfgPotInfo.getId());
            potProduct.setType(1);//默认就是常用产品
            cfgPotProductService.save(potProduct);
        }
    }

    @Override
    @Transactional
    public void updatePot(CfgPotInfo cfgPotInfo) {
        int count = this.count(new LambdaQueryWrapper<CfgPotInfo>().eq(CfgPotInfo::getNumberNo, cfgPotInfo.getNumberNo()).ne(CfgPotInfo::getId, cfgPotInfo.getId()).ne(CfgPotInfo::getStatus, -1));
        if (count > 0) {
            throw new RRException("编号已存在");
        }
        CfgPotInfo db = this.getById(cfgPotInfo.getId());//取出对比 记日志
        this.updateById(cfgPotInfo);
        Integer potId = cfgPotInfo.getId();
        CfgPotProduct potProduct = cfgPotInfo.getPotProduct();
        CfgPotProduct dbProduct = cfgPotProductService.getOne(new LambdaQueryWrapper<CfgPotProduct>().eq(CfgPotProduct::getPotId, potId));
        CfgPotProduct dbProduct2 = null;
        if (null != dbProduct) {
            dbProduct2 = new CfgPotProduct();
            CopyUtils.copyProperties(dbProduct, dbProduct2);
        }

        List<CfgPotProduct> dbProducts = new ArrayList<>();
        if (null != dbProduct2) {
            dbProducts.add(dbProduct2);
        }
        if (null != potProduct) {
            if (null == dbProduct) {
                potProduct.setType(1);
                potProduct.setPotId(potId);
                cfgPotProductService.save(potProduct);
            } else {
                dbProduct.setProductId(potProduct.getProductId());
                dbProduct.setName(potProduct.getName());
                cfgPotProductService.updateById(dbProduct);
            }
        } else {
            if (null == dbProduct) {
                potProduct = new CfgPotProduct();
                potProduct.setType(1);
                potProduct.setPotId(potId);
                cfgPotProductService.save(potProduct);
            } else {
                UpdateWrapper<CfgPotProduct> uw = new UpdateWrapper<>();
                uw.set("product_id", null);
                uw.set("name", null);
                uw.eq("id", dbProduct.getId());
                cfgPotProductService.update(new CfgPotProduct(), uw);
            }
        }
        taskExecutor.submit(new PotLog(cfgPotInfo, db, dbProducts, MDC.get("deptUser")));
    }

    @Override
    public List<CfgPotRelate> getRelateObject(Integer potId) {
        List<CfgPotRelate> list = potRelateService.list(new LambdaQueryWrapper<CfgPotRelate>().eq(CfgPotRelate::getPotId, potId));
        List<RelateObj> relateObjs;
        RelateObj ro;
        for (CfgPotRelate re : list) {
            relateObjs = new ArrayList<>();
            ro = new RelateObj(re.getRelateId(), re.getName());
            relateObjs.add(ro);
            re.setSubRelates(relateObjs);
        }
        return list;
    }

    @Override
    @Transactional
    public void updateRelateObject(List<CfgPotRelate> relates) {
        //全删全增
        Integer potId = relates.get(0).getPotId();
        if (null == potId) {
            throw new RRException("参数有误");
        }
        potRelateService.remove(new LambdaQueryWrapper<CfgPotRelate>().eq(CfgPotRelate::getPotId, potId));
        potRelateService.saveBatch(relates);
    }

    @Override
    public PageUtils logList(Map<String, Object> params) {
        Page<CfgPotLog> page = new Query<CfgPotLog>(params).getPage();
        potLogService.page(page.setDesc("id"), new LambdaQueryWrapper<CfgPotLog>().eq(CfgPotLog::getPotId, params.get("id")));
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void updateRfid(CfgPotInfo cfgPotInfo) {
        CfgPotInfo old = this.getById(cfgPotInfo.getId());
        if (StringUtils.isEmpty(cfgPotInfo.getRfid())) {
            this.update(new CfgPotInfo(), new UpdateWrapper<CfgPotInfo>().set(CfgPotInfo.RFID, "").eq(CfgPotInfo.ID, cfgPotInfo.getId()));
        } else {
            this.updateById(cfgPotInfo);
        }
        if (!ObjectUtils.nullSafeEquals(cfgPotInfo.getRfid(), old.getRfid())) {
            String rfidInfo = old.getRfid() + " → " + cfgPotInfo.getRfid();
            CfgPotLog log = new CfgPotLog();
            log.setPotId(cfgPotInfo.getId());
            log.setDeptUser(MDC.get("deptUser"));
            log.setRfidInfo(rfidInfo);
            log.setWorkAreaInfo("");
            log.setProductInfo("");
            potLogService.save(log);
        }
    }

}
